package com.ccsoft.multithread.test;

import lombok.extern.slf4j.Slf4j;

/**
 * @author chanchaw
 * @create 2022-08-05 14:44
 * 两阶段终止模式
 */
@Slf4j(topic = "NO4TwoPhaseTerminate")
public class No4TwoPhaseTerminate {

    public static void main(String[] args) {
        MonitorUtil monitorUtil = new MonitorUtil();
        monitorUtil.start();
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        monitorUtil.stop();

    }

    public void twoPhase(){
        Thread monitorThread = new Thread(()->{
        Thread currentThread = Thread.currentThread();

        while(true){
        if(currentThread.isInterrupted()){
            log.error("处理后事，准备结束监控线程。");
            log.error("已结束监控线程！");
            break;
        }

        log.error("开始执行复杂计算...");
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // sleep 中被 interrupt 会报异常 InterruptedException
            // 同时清除 isInterrupted 标识，所以要重新设置该标识
            e.printStackTrace();
            currentThread.interrupt();
        }
        log.error("计算完毕~~~");
        }
        },"monitorThread");



        monitorThread.start();
        try {
        Thread.sleep(300);
        } catch (InterruptedException e) {
        e.printStackTrace();
        }

        log.error("主线程打断监控线程");
        monitorThread.interrupt();
    }
}

@Slf4j(topic = "monitor")
class MonitorUtil {
    private volatile boolean stop = false;
    public void start(){
        new Thread(()->{
            while(true){
                if(stop){
                    log.error("准备优雅退出");
                    break;
                }

                log.error("开始计算...");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.error("计算结束~~~");
            }
        },"monitorThread").start();
    }

    public void stop(){
        stop = true;
    }
}
